package cn.mrlong.basicframework.utils;

import com.alibaba.fastjson.JSON;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

public class GsonUtil {

    /**
     * Json to bean
     *
     * @param val
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T paseFromStringToBean(String val, Class<T> tClass) throws Exception {
        if (null == val || "null".equals(val) || val.trim().equals("") || val.length() == 0) {
            throw new RuntimeException("服务器返回数据错误！");
        }
        T t = JSON.parseObject(val, tClass);
        return t;
    }

    /**
     * bean to json
     *
     * @param obj
     * @return
     */
    public static String paseFromBeanToString(Object obj) {
        String val = "";
        val = JSON.toJSONString(obj);
        return val;
    }

    /**
     * String to list<bean>
     *
     * @param val
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> List<T> parseFromStringToList(String val, Class<T> tClass) throws Exception {
        if (null == val || "null".equals(val) || val.trim().equals("") || val.length() == 0) {
            throw new RuntimeException("解析的数据不能为空！");
        }
        List arrayList = new ArrayList();
        JSONArray array = new JSONArray(val);
        for (int i = 0; i < array.length(); i++) {
            arrayList.add(JSON.parseArray(array.get(i).toString(), tClass));
        }
        return arrayList;
    }

}